// 录制管理器
// 负责管理录制会话、WebSocket连接和状态轮询

/**
 * 录制管理器类 - 负责管理录制会话、WebSocket连接和状态轮询
 */
export class RecordingManager {
  constructor() {
    // 录制状态
    this.isRecording = false
    this.recordingSession = null
    this.websocket = null
    this.recordedSteps = []
    this.sessionId = null
    this.currentUrl = ''
    this.eventListeners = new Map()
    this.backendAvailable = false
    
    // 配置 - 根据后端 API 文档
    // 直接访问后端服务，不再使用代理
    this.config = {
      apiBaseUrl: 'http://localhost:23679', // 直接访问后端服务
      startEndpoint: '/start-codegen',
      stopEndpoint: '/stop-codegen',
      healthEndpoint: '/health',
      wsPort: 3001, // WebSocket端口 (如果后端支持)
      wsPath: '/recording',
      reconnectAttempts: 3,
      reconnectDelay: 1000,
      pollingInterval: 500 // 状态轮询间隔 (毫秒)
    }
    
    // 状态轮询
    this.statusPollingInterval = null
    this.lastOutputFile = null
  }

  /**
   * 初始化录制管理器
   */
  async init() {
    console.log('初始化录制管理器...')
    
    // 强制清理可能残留的状态
    this.forceCleanup()
    
    // 设置事件监听器
    this.setupEventListeners()
    
    // 不再检查后端可用性，直接标记为可用
    this.backendAvailable = true
    
    console.log('录制管理器初始化完成')
  }

  /**
   * 强制清理残留状态
   */
  forceCleanup() {
    try {
      // 清理WebSocket连接
      if (this.websocket) {
        try {
          this.websocket.close()
        } catch (e) {
          // 忽略关闭错误
        }
        this.websocket = null
      }
      
      // 停止状态轮询
      this.stopStatusPolling()
      
      // 清理定时器
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer)
        this.reconnectTimer = null
      }
      
      // 重置录制状态
      this.isRecording = false
      this.recordingSession = null
      this.recordedSteps = []
      this.sessionId = null
      this.currentUrl = ''
      this.backendAvailable = false
      
      console.log('录制状态已清理')
    } catch (error) {
      console.warn('清理录制状态时出错:', error)
    }
  }


  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    if (typeof window === 'undefined') return
    
    // 监听录制开始事件
    document.addEventListener('startRecording', (event) => {
      this.startRecording(event.detail.url)
    })

    // 监听录制停止事件
    document.addEventListener('stopRecording', () => {
      this.stopRecording()
    })

    // 监听页面卸载事件
    window.addEventListener('beforeunload', () => {
      this.forceCleanup()
    })
    
    // 监听页面隐藏事件
    document.addEventListener('visibilitychange', () => {
      if (document.hidden && this.isRecording) {
        this.forceCleanup()
      }
    })
  }

  /**
   * 开始录制
   * @param {string} url - 要录制的URL
   */
  async startRecording(url = 'https://www.baidu.com') {
    if (this.isRecording) {
      throw new Error('录制已在进行中')
    }

    try {
      this.currentUrl = url
      this.sessionId = this.generateSessionId()
      this.recordedSteps = []

      console.log(`开始录制: ${this.currentUrl}`)

      // 启动后端录制服务
      await this.startBackendRecording()

      // 建立WebSocket连接（如果后端支持）
      try {
        await this.connectWebSocket()
      } catch (wsError) {
        console.warn('WebSocket连接失败，使用基础录制模式（正常现象）')
      }

      // 更新录制状态
      this.isRecording = true

      // 触发录制开始事件
      this.dispatchEvent('recordingStarted', {
        sessionId: this.sessionId,
        url: this.currentUrl,
        timestamp: Date.now(),
        mode: this.recordingSession?.mode || 'unknown'
      })

      console.log('录制已开始')

      return {
        success: true,
        sessionId: this.sessionId,
        mode: this.recordingSession?.mode || 'codegen',
        message: 'Codegen 录制已启动！Playwright 浏览器即将自动打开，请在其中进行操作。'
      }

    } catch (error) {
      console.error('启动录制失败:', error)
      await this.handleRecordingError(error)
      throw error
    }
  }

  /**
   * 停止录制
   */
  async stopRecording() {
    if (!this.isRecording) {
      return { success: false, error: '当前没有进行录制' }
    }

    try {
      console.log('停止录制...')

      // 关闭WebSocket连接
      this.disconnectWebSocket()

      // 停止后端录制
      await this.stopBackendRecording()

      // 更新录制状态
      this.isRecording = false

      // 处理录制结果
      const recordingResult = {
        sessionId: this.sessionId,
        url: this.currentUrl,
        steps: this.recordedSteps,
        duration: Date.now() - (this.recordingSession?.startTime || Date.now()),
        timestamp: Date.now(),
        mode: this.recordingSession?.mode || 'codegen'
      }

      // 触发录制完成事件
      this.dispatchEvent('recordingCompleted', recordingResult)

      console.log(`录制完成，共记录 ${this.recordedSteps.length} 个步骤`)

      // 保存步骤数据用于返回
      const stepsToReturn = [...this.recordedSteps]

      // 重置状态（但保留步骤数据）
      this.isRecording = false
      this.recordingSession = null
      this.sessionId = null
      this.currentUrl = ''
      this.disconnectWebSocket()
      this.stopStatusPolling()

      return {
        success: true,
        ...recordingResult,
        steps: stepsToReturn
      }

    } catch (error) {
      console.error('停止录制失败:', error)
      await this.handleRecordingError(error)
      throw error
    }
  }

  /**
   * 启动后端录制服务 (Codegen)
   */
  async startBackendRecording() {
    // 根据后端文档：POST /start-codegen
    const startUrl = `${this.config.apiBaseUrl}${this.config.startEndpoint}`
    
    console.log('启动 Codegen 录制:', startUrl)
    console.log('config.apiBaseUrl:', this.config.apiBaseUrl)
    console.log('config.startEndpoint:', this.config.startEndpoint)
    
    const response = await fetch(startUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
        'X-Requested-With': 'XMLHttpRequest'
      },
      mode: 'cors',
      credentials: 'include',
      body: JSON.stringify({
        url: this.currentUrl
      })
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`启动录制服务失败 (${response.status}): ${errorText}`)
    }

    const result = await response.json()
    
    // 根据后端响应格式：{ success, sessionId, outputFile, message, timestamp }
    if (result.success) {
      this.recordingSession = {
        sessionId: result.sessionId,
        outputFile: result.outputFile,
        startTime: Date.now(),
        mode: 'codegen',
        timestamp: result.timestamp
      }
      
      console.log('Codegen 录制服务已启动')
      console.log('  - Session ID:', result.sessionId)
      console.log('  - Output File:', result.outputFile)
      console.log('  - Message:', result.message)
      
      this.backendAvailable = true
    } else {
      throw new Error(result.error || result.message || '启动录制失败')
    }
  }

  /**
   * 停止后端录制服务
   */
  async stopBackendRecording() {
    if (!this.recordingSession) {
      throw new Error('没有活跃的录制会话')
    }

    // 停止状态轮询
    this.stopStatusPolling()

    // 根据后端文档：POST /stop-codegen
    const stopUrl = `${this.config.apiBaseUrl}${this.config.stopEndpoint}`
    
    console.log('停止 Codegen 录制:', stopUrl)
    
    const response = await fetch(stopUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
        'X-Requested-With': 'XMLHttpRequest'
      },
      mode: 'cors',
      credentials: 'include',
      body: JSON.stringify({})
    })
    console.log("后端返回结果"+JSON.stringify(response))
    if (!response.ok) {
      // 尝试获取错误详情
      let errorText = ''
      try {
        errorText = await response.text()
        console.error('错误响应内容:', errorText)
      } catch (e) {
        errorText = '无法读取错误响应'
      }
      
      // 根据状态码提供更具体的错误信息
      let errorMessage = ''
      if (response.status === 500) {
        errorMessage = '后端服务器内部错误 (500)'
      } else if (response.status === 404) {
        errorMessage = '停止录制接口不存在 (404)'
      } else if (response.status === 400) {
        errorMessage = '请求参数错误 (400)'
      } else {
        errorMessage = `HTTP ${response.status} 错误`
      }
      
      throw new Error(`${errorMessage}: ${errorText}`)
    }

    const result = await response.json()
    
    // 根据后端响应格式处理
    if (result.success) {
      console.log('Codegen 录制已停止')
      console.log('  - Session ID:', result.sessionId)
      console.log('  - Output File:', result.outputFile)
      console.log('  - Script Size:', result.scriptSize, '字符')
      console.log('  - Script Exists:', result.scriptExists)
      console.log('  - Process Killed:', result.processKilled)
      console.log("后端返回结果"+JSON.stringify(result))
      // 解析脚本内容为步骤
      if (result.scriptContent) {
        this.recordedSteps = this.parseScriptToSteps(result.scriptContent)
        console.log("解析得到步骤"+JSON.stringify(this.recordedSteps))
        console.log(`解析得到 ${this.recordedSteps.length} 个步骤`)
      }
      
      // 保存脚本内容
      this.lastScriptContent = result.scriptContent
      this.lastOutputFile = result.outputFile
      
      return result
    } else {
      throw new Error(result.error || '停止录制失败')
    }
  }

  /**
   * 建立WebSocket连接
   */
  async connectWebSocket() {
    return new Promise((resolve, reject) => {
      try {
        const wsUrl = `ws://localhost:${this.config.wsPort}${this.config.wsPath}/${this.sessionId}`
        console.log('连接WebSocket:', wsUrl)
        
        this.websocket = new WebSocket(wsUrl)

        this.websocket.onopen = () => {
          console.log('WebSocket连接已建立')
          resolve()
        }

        this.websocket.onmessage = (event) => {
          this.handleWebSocketMessage(event)
        }

        this.websocket.onerror = (error) => {
          console.warn('WebSocket连接错误:', error)
          resolve() // 继续使用模拟模式
        }

        this.websocket.onclose = () => {
          console.log('WebSocket连接已关闭')
        }

        // 连接超时处理
        setTimeout(() => {
          if (this.websocket && this.websocket.readyState !== WebSocket.OPEN) {
            console.warn('WebSocket连接超时，使用模拟模式')
            resolve()
          }
        }, 3000)

      } catch (error) {
        console.warn('WebSocket不可用，使用模拟模式:', error)
        resolve()
      }
    })
  }

  /**
   * 断开WebSocket连接
   */
  disconnectWebSocket() {
    if (this.websocket) {
      try {
        this.websocket.close()
      } catch (e) {
        // 忽略关闭错误
      }
      this.websocket = null
    }
  }

  /**
   * 处理WebSocket消息
   */
  handleWebSocketMessage(event) {
    try {
      const data = JSON.parse(event.data)
      console.log('WebSocket消息:', data)
      
      switch (data.type) {
        case 'connected':
          console.log('WebSocket已连接到会话:', data.sessionId)
          break
          
        case 'step':
          // 实时接收录制步骤
          this.addRecordedStep(data.step)
          break
          
        case 'error':
          console.error('录制错误:', data.error)
          this.dispatchEvent('recordingError', { error: data.error })
          break
          
        case 'status':
          this.updateRecordingStatus(data.status)
          break
          
        case 'stopped':
          console.log('录制已停止')
          if (data.steps) {
            this.recordedSteps = data.steps
          }
          break
          
        default:
          console.log('未知WebSocket消息类型:', data.type)
      }
    } catch (error) {
      console.error('处理WebSocket消息失败:', error)
    }
  }

  /**
   * 添加录制步骤
   */
  addRecordedStep(step) {
    const processedStep = {
      id: this.generateStepId(),
      stepNumber: this.recordedSteps.length + 1,
      timestamp: new Date().toISOString(),
      ...step
    }

    this.recordedSteps.push(processedStep)

    // 触发步骤添加事件
    this.dispatchEvent('stepRecorded', {
      step: processedStep,
      totalSteps: this.recordedSteps.length,
      sessionId: this.sessionId
    })

    console.log(`步骤 ${processedStep.stepNumber}: ${processedStep.type} - ${processedStep.name}`)
  }

  /**
   * 开始状态轮询
   */
  startStatusPolling() {
    if (this.statusPollingInterval) {
      clearInterval(this.statusPollingInterval)
    }
    
    const apiBaseUrl = 'http://localhost:8080/api/commands'
    
    // 立即检查一次
    this.checkRecordingStatus()
    
    // 每500毫秒轮询一次
    this.statusPollingInterval = setInterval(async () => {
      try {
        if (!this.recordingSession || !this.recordingSession.taskId) {
          return
        }
        
        const response = await fetch(`${apiBaseUrl}/recording/status/${this.recordingSession.taskId}`)
        if (response.ok) {
          const result = await response.json()
          if (result.success) {
            this.updateRecordingStatus({
              status: result.data.status,
              message: result.data.message,
              outputFile: result.data.outputFile
            })
            
            // 检查是否有新的输出文件
            if (result.data.outputFile && result.data.outputFile !== this.lastOutputFile) {
              this.lastOutputFile = result.data.outputFile
              console.log('检测到新的输出文件:', result.data.outputFile)
              await this.importLatestRecordingFile(result.data.outputFile)
            }
            
            // 如果任务完成，停止轮询
            if (result.data.status === 'COMPLETED' || result.data.status === 'FAILED') {
              this.stopStatusPolling()
              
              // 最后一次导入确保获取所有步骤
              if (result.data.outputFile) {
                await this.importLatestRecordingFile(result.data.outputFile)
              }
            }
          }
        }
      } catch (error) {
        console.error('状态轮询失败:', error)
      }
    }, this.config.pollingInterval)
  }

  /**
   * 停止状态轮询
   */
  stopStatusPolling() {
    if (this.statusPollingInterval) {
      clearInterval(this.statusPollingInterval)
      this.statusPollingInterval = null
    }
  }

  /**
   * 检查录制状态
   */
  async checkRecordingStatus() {
    try {
      if (!this.recordingSession || !this.recordingSession.sessionId) {
        return
      }
      
      const taskId = this.recordingSession.taskId || this.recordingSession.sessionId
      const statusUrl = `http://localhost:8080/api/commands/recording/status/${taskId}`
      
      const response = await fetch(statusUrl)
      if (!response.ok) {
        return
      }
      
      const result = await response.json()
      
      if (result.success && result.data) {
        this.updateRecordingStatus(result.data)
      }
    } catch (error) {
      console.error('检查录制状态失败:', error)
    }
  }

  /**
   * 导入最新的录制文件
   */
  async importLatestRecordingFile(outputFile) {
    try {
      if (!outputFile) return
      
      const fileName = outputFile.includes('/') ? outputFile.split('/').pop() : outputFile
      console.log('导入录制文件:', fileName)
      
      const response = await fetch(`http://localhost:8080/api/commands/files/read?filename=${encodeURIComponent(fileName)}`)
      if (!response.ok) {
        console.warn('无法读取录制文件:', fileName)
        return
      }
      
      const fileResult = await response.json()
      if (!fileResult.success || !fileResult.data) {
        console.warn('文件内容为空:', fileName)
        return
      }
      
      const scriptContent = fileResult.data
      console.log('读取到脚本内容，长度:', scriptContent.length)
      
      // 解析脚本内容为步骤
      const parsedSteps = this.parseScriptToSteps(scriptContent)
      
      if (parsedSteps.length > 0) {
        const currentStepCount = this.recordedSteps.length
        
        if (parsedSteps.length > currentStepCount) {
          const newSteps = parsedSteps.slice(currentStepCount)
          
          newSteps.forEach((step, index) => {
            const processedStep = {
              ...step,
              stepNumber: currentStepCount + index + 1,
              timestamp: new Date().toISOString()
            }
            
            this.recordedSteps.push(processedStep)
            this.dispatchStepRecordedEvent(processedStep)
          })
          
          console.log(`🔄 实时同步: 新增 ${newSteps.length} 个步骤，总计 ${this.recordedSteps.length} 个步骤`)
          this.updateRecordingStatus()
        }
      }
      
    } catch (error) {
      console.error('导入录制文件失败:', error)
    }
  }

  /**
   * 解析脚本内容为步骤 - 简化版，只解析关键操作
   */
  parseScriptToSteps(scriptContent) {
    const steps = []
    
    if (!scriptContent || typeof scriptContent !== 'string') {
      return steps
    }
    
    const lines = scriptContent.split('\n')
    let stepIndex = 0
    let inAsyncFunction = false
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim()
      
      // 跳过空行、注释、导入语句、函数定义等
      if (!line || line.startsWith('//') || line.startsWith('import') || 
          line.startsWith('const {') || line.startsWith('test(') || 
          line === '}' || line === '});' || line === '{' ||
          line.startsWith('(async () => {') || line.startsWith('})();')) {
        
        if (line.startsWith('(async () => {')) {
          inAsyncFunction = true
        }
        continue
      }
      
      // 跳过函数外的代码
      if (!inAsyncFunction) {
        continue
      }
      
      // 跳过变量赋值和Promise处理
      if (line.includes('=') && (line.includes('waitForEvent') || line.includes('Promise'))) {
        continue
      }
      
      // 只解析关键操作
      const step = this.parseLineToStep(line, stepIndex)
      if (step) {
        steps.push(step)
        stepIndex++
      }
    }
    
    return steps
  }

  /**
   * 解析单行代码为步骤 - 简化版，只解析关键操作
   */
  parseLineToStep(line, stepIndex) {
    const cleanLine = line.replace(/^\s*await\s+/, '').replace(/;?\s*$/, '')
    
    // 1. 导航操作 - page.goto()
    if (cleanLine.includes('.goto(')) {
      const urlMatch = cleanLine.match(/\.goto\(['"`]([^'"`]+)['"`]\)/)
      return {
        type: 'navigation',
        name: '导航到页面',
        description: `打开网页: ${urlMatch ? urlMatch[1] : ''}`,
        url: urlMatch ? urlMatch[1] : '',
        stepNumber: stepIndex + 1
      }
    }
    
    // 2. 通过角色点击 - getByRole().click()
    if (cleanLine.includes('.getByRole(') && cleanLine.includes('.click()')) {
      const roleMatch = cleanLine.match(/\.getByRole\(['"`]([^'"`]+)['"`],\s*\{\s*name:\s*['"`]([^'"`]+)['"`]\s*\}\)/)
      if (roleMatch) {
        return {
          type: 'click',
          name: '点击链接',
          description: `点击${roleMatch[1]}: ${roleMatch[2]}`,
          elementName: roleMatch[2],
          stepNumber: stepIndex + 1
        }
      }
    }
    
    // 3. 通过定位器点击 - locator().click()
    if (cleanLine.includes('.locator(') && cleanLine.includes('.click()')) {
      // 处理文本过滤点击
      if (cleanLine.includes('.filter(')) {
        const filterMatch = cleanLine.match(/\.locator\(['"`]([^'"`]+)['"`]\)\.filter\(\{\s*hasText:\s*\/([^\/]+)\/\s*\}\)/)
        if (filterMatch) {
          return {
            type: 'click',
            name: '点击文本元素',
            description: `点击包含"${filterMatch[2]}"的${filterMatch[1]}`,
            textContent: filterMatch[2],
            stepNumber: stepIndex + 1
          }
        }
      }
      
      // 处理链式定位器点击
      if (cleanLine.includes('.getByRole(')) {
        const chainMatch = cleanLine.match(/\.locator\(['"`]([^'"`]+)['"`]\)\.getByRole\(['"`]([^'"`]+)['"`],\s*\{\s*name:\s*['"`]([^'"`]+)['"`],\s*exact:\s*true\s*\}\)/)
        if (chainMatch) {
          return {
            type: 'click',
            name: '点击精确链接',
            description: `在${chainMatch[1]}中点击: ${chainMatch[3]}`,
            elementName: chainMatch[3],
            stepNumber: stepIndex + 1
          }
        }
      }
    }
    
    // 4. 输入操作 - fill() 或 type()
    if (cleanLine.includes('.fill(') || cleanLine.includes('.type(')) {
      // 处理通过getByRole调用的fill操作
      if (cleanLine.includes('.getByRole(') && cleanLine.includes('.fill(')) {
        const roleFillMatch = cleanLine.match(/\.getByRole\(['"`]([^'"`]+)['"`],\s*\{\s*name:\s*['"`]([^'"`]+)['"`]\s*\}\)\.fill\(['"`]([^'"`]*)['"`]\)/)
        if (roleFillMatch) {
          return {
            type: 'input',
            name: '输入文本',
            description: `在${roleFillMatch[1]}中输入: ${roleFillMatch[3]}`,
            elementName: roleFillMatch[2],
            value: roleFillMatch[3],
            stepNumber: stepIndex + 1
          }
        }
      }
      
      // 处理通过选择器调用的fill操作
      const matches = cleanLine.match(/\.(fill|type)\(['"`]([^'"`]+)['"`],\s*['"`]([^'"`]*)['"`]\)/)
      if (matches) {
        return {
          type: 'input',
          name: '输入文本',
          description: `在${matches[2]}中输入: ${matches[3]}`,
          value: matches[3],
          stepNumber: stepIndex + 1
        }
      }
    }
    
    // 5. 关闭操作 - close() (跳过不展示)
    if (cleanLine.includes('.close()')) {
      return null
    }
    
    return null
  }



  /**
   * 更新录制状态
   */
  updateRecordingStatus(status) {
    this.dispatchEvent('recordingStatusChanged', {
      status,
      sessionId: this.sessionId,
      stepCount: this.recordedSteps.length
    })
  }

  /**
   * 触发步骤录制事件
   */
  dispatchStepRecordedEvent(step) {
    if (typeof window !== 'undefined') {
      const event = new CustomEvent('stepRecorded', {
        detail: {
          step: step,
          totalSteps: this.recordedSteps.length,
          sessionId: this.sessionId
        }
      })
      window.dispatchEvent(event)
    }
  }

  /**
   * 处理录制错误
   */
  async handleRecordingError(error) {
    console.error('录制错误:', error)
    
    this.forceCleanup()

    this.dispatchEvent('recordingError', {
      error: error.message,
      sessionId: this.sessionId,
      timestamp: Date.now()
    })

    this.resetRecordingState()
  }

  /**
   * 重置录制状态
   */
  resetRecordingState() {
    this.isRecording = false
    this.recordingSession = null
    this.recordedSteps = []
    this.sessionId = null
    this.currentUrl = ''
    
    this.disconnectWebSocket()
    this.stopStatusPolling()
  }

  /**
   * 生成会话ID
   */
  generateSessionId() {
    return `rec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 生成步骤ID
   */
  generateStepId() {
    return `step_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`
  }

  /**
   * 触发事件
   */
  dispatchEvent(type, detail) {
    if (typeof window !== 'undefined') {
      const event = new CustomEvent(type, { detail })
      window.dispatchEvent(event)
      
      // 同时触发更新事件（兼容性）
      if (type === 'stepRecorded' || type === 'recordingStatusChanged') {
        const updateEvent = new CustomEvent('recordingStatusUpdated', {
          detail: {
            isRecording: this.isRecording,
            stepCount: this.recordedSteps.length,
            sessionId: this.sessionId,
            steps: this.recordedSteps,
            ...detail
          }
        })
        window.dispatchEvent(updateEvent)
      }
    }
  }

  /**
   * 获取录制状态
   */
  getRecordingStatus() {
    return {
      isRecording: this.isRecording,
      sessionId: this.sessionId,
      url: this.currentUrl,
      stepCount: this.recordedSteps.length,
      duration: this.recordingSession ? Date.now() - this.recordingSession.startTime : 0,
      mode: this.recordingSession?.mode || 'unknown'
    }
  }

  /**
   * 获取录制的步骤
   */
  getRecordedSteps() {
    return [...this.recordedSteps]
  }

  /**
   * 暂停录制
   */
  pauseRecording() {
    if (!this.isRecording) return

    this.dispatchEvent('recordingPaused', {
      sessionId: this.sessionId,
      stepCount: this.recordedSteps.length
    })
  }

  /**
   * 恢复录制
   */
  resumeRecording() {
    if (!this.isRecording) return

    this.dispatchEvent('recordingResumed', {
      sessionId: this.sessionId,
      stepCount: this.recordedSteps.length
    })
  }
}

// 创建全局录制管理器实例
export const recordingManager = new RecordingManager()

// 导出便捷方法
export const startRecording = (url) => recordingManager.startRecording(url)
export const stopRecording = () => recordingManager.stopRecording()
export const getRecordingStatus = () => recordingManager.getRecordingStatus()
export const initRecordingManager = () => recordingManager.init()

